import face_recognition
import os

# 加载已知人脸照片库
known_face_encodings = []
known_face_names = []

# 照片库所在的目录
known_faces_dir = "../lib"
for filename in os.listdir(known_faces_dir):
    if filename.endswith(('.png', '.jpg', '.jpeg')):
        image = face_recognition.load_image_file(os.path.join(known_faces_dir, filename))
        face_encoding = face_recognition.face_encodings(image)
        if face_encoding:
            known_face_encodings.append(face_encoding[0])
            known_face_names.append(os.path.splitext(filename)[0])

# 加载新照片
unknown_image = face_recognition.load_image_file("../lib/4.jpg")

# 查找新照片中所有人脸的位置和特征编码
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)

# 遍历新照片中检测到的每个人脸
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
    # 计算与已知人脸的距离（距离越小，匹配度越高）
    face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
    best_match_index = face_distances.argmin()
    name = known_face_names[best_match_index]
    similarity = (1 - face_distances[best_match_index]) * 100  # 将距离转换为匹配度百分比

    print(f"检测到的人脸位置: 上={top}, 右={right}, 下={bottom}, 左={left}")
    print(f"最匹配的人物: {name}")
    print(f"匹配度: {similarity:.2f}%")
    print("-" * 30)
